<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/admin/spumanage/spuaccount">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>相册管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-s-tools"></i> &nbsp; 管理信息
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right;">
          <div class="grid-content bg-purple">
            <el-button size="small" type="primary"
                       icon="el-icon-circle-plus-outline"
                       @click="addDialogVisible = true">新建相册
            </el-button>
            <el-button size="small" type="primary"
                       icon="el-icon-sort">排序设置
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div class="divider"></div>

      <el-row :gutter="15" class="whererow">
        <el-col :span="5" style="line-height: 32px">当前共{{ tableData.length }}个商品相册</el-col>
        <el-col :span="4" style="line-height: 32px">已选择{{ tableChecked.length }}项</el-col>
        <el-col :span="6">
          <el-input
              v-model="search" type="text" size="small" placeholder="请输入相册名称">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button-group>
            <el-button type="primary" icon="el-icon-edit"></el-button>
            <el-button type="primary" icon="el-icon-share"></el-button>
            <el-button type="primary" icon="el-icon-delete"
                       @click="batchDelete(tableChecked)"></el-button>
          </el-button-group>
        </el-col>
      </el-row>
    </div>
    <!--表单-->
    <el-table :data="tableData" border style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="description" label="简介" align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" align="center"></el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.id)"></el-button>
          <el-button circle icon="el-icon-delete" size="mini" type="danger"
                     @click="openDeleteConfirm(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 新增相册的弹窗 -->
    <el-dialog width="40%" title="新建相册" :visible.sync="addDialogVisible"
               :modal-append-to-body="false">
      <el-row>
        <el-col :span="24">
          <el-form ref="album" :model="album" label-width="80px" size="small">
            <el-form-item label="相册名称" prop="name">
              <el-input v-model="album.name"
                        maxlength="15" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="相册描述" prop="description">
              <el-input type="textarea" v-model="album.description"
                        maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="排序序号" prop="sort">
              <el-input maxlength="5" v-model="album.sort"></el-input>
            </el-form-item>
            <el-form-item size="large">
              <el-button type="primary" @click="submitForm('album')">保存</el-button>
              <el-button @click="resetForm('album')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import photoAlbumItem from "@/components/PhotoAlbumItem.vue";

export default {
  components: {
    photoAlbumItem,
  },
  data() {
    return {
      album: {
        name: '',
        description: '',
        sort: ''
      },
      addDialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      search: '',
      selectRoles: '',

      currentPage: 3,
      input: '',
      value: '',
      tableData: [],
      tableChecked: []
    }
  },

  mounted() {
    this.loadAlbums();
  },

  methods: {
    /** 加载相册列表 */
    loadAlbums() {
      console.log('loadAlbums()');
      let url = 'http://localhost:9080/albums';
      console.log('url = ' + url);
      let jwt = localStorage.getItem('jwt');
      console.log('jwt = ' + jwt);
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let json = response.data;
        if (json.code == 20000) {
          this.tableData = json.data;
        } else {
          this.$message.error(response.data.message);
        }
      });
    },
    /** 新建相册 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9080/albums/add-new';
          console.log('url >>> ' + url);
          console.log('data >>> ');
          console.log(this.ruleForm);
          this.axios
              .create({headers: {'Authorization': localStorage.getItem('jwt')}})
              .post(url, this.album).then((response) => {
            console.log(response.data);
            if (response.data.code == 20000) {
              this.$message({
                message: '添加相册成功！',
                type: 'success'
              });
            } else {
              this.$message.error(response.data.message);
            }
          }).catch(err => {
            console.log('响应结果为失败！');
          })
        } else {
          console.log('error submit!!');
          return false;
        }
        this.loadAlbums();
      });
    },
    /** 重置提交信息 */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /** 删除相册 */
    handleDelete(id) {
      console.log("将要删除id=" + id + "的相册数据.....");
      let url = 'http://localhost:9080/albums/' + id + '/delete';
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let json = response.data;
        if (json.code == 20000) {
          this.$message({
            message: '删除相册成功！',
            type: 'success'
          });
        } else {
          this.$message.error(response.data.message);
        }
        this.loadAlbums();
      }).catch(() => {
        // 执行到此处，通常是没有权限，例如没有携带JWT，被服务器端视为未登录，或当前登录的账号确实无权限
        this.$message.error('删除相册失败，服务器忙，请稍后再次尝试！');
      });
    },
    /** 删除确定 */
    openDeleteConfirm(id) {
      this.$confirm('此操作将永久删除该相册, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(id);
      }).catch(() => {
      });
    },
    //批量删除
    batchDelete(rows) {
      var ids = [];
      rows.forEach(element => {
        ids.push(element.id)
      })
      console.log("将要删除id=" + ids + "的相册数据.....");
      let url = 'http://localhost:9080/albums/ids/delete';
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .post(url, ids).then((response) => {
        let json = response.data;
        if (json.code == 20000) {
          this.$message({
            message: '删除相册成功！',
            type: 'success'
          });
        } else {
          this.$message.error(response.data.message);
        }
        this.loadAlbums();
      }).catch(() => {
        // 执行到此处，通常是没有权限，例如没有携带JWT，被服务器端视为未登录，或当前登录的账号确实无权限
        this.$message.error('删除相册失败，服务器忙，请稍后再次尝试！');
      });
    },
    handleSelectionChange(val) {
      this.tableChecked = val;
    }
  }
};
</script>
